package com.caishi.lkx.user.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.caishi.lkx.common.BaseApi;
import com.caishi.lkx.common.EncryptionApi;
import com.caishi.lkx.common.PushService;
import com.caishi.lkx.common.config.DiamondConfig;
import com.caishi.lkx.common.context.RequireContext;
import com.caishi.lkx.common.fliter.TokenFilter;
import com.caishi.lkx.common.ienum.PlatformType;
import com.caishi.lkx.common.role.Role;
import com.caishi.lkx.common.role.Roles;
import com.caishi.lkx.user.dto.IndexMemberSearchVo;
import com.caishi.lkx.user.dto.RegisterMemberDto;
import com.caishi.lkx.user.ienum.type.*;
import com.caishi.lkx.user.model.*;
import com.caishi.lkx.user.service.*;
import com.zzw.common.Wrappers;
import com.zzw.common.exception.BizException;
import com.zzw.common.exception.BizRuntimeException;
import com.zzw.common.utils.CommonUtil;
import com.zzw.common.utils.MD5Util;

import com.caishi.lkx.user.login.LoginServiceComposite;
import com.caishi.lkx.user.mongo.UserLoginVersionMongoRepository;
import com.caishi.lkx.user.userlog.NormalLogRecordsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.time.*;
import java.util.*;
import java.util.concurrent.TimeoutException;

import static com.caishi.lkx.common.fliter.TokenFilter.ZT_ENCODE;


/**
 * @author by keray
 * date:2021/7/8 2:51 下午
 */
@Tag(name = "学生相关接口")
@RestController
@RequestMapping("/user/cu/member")
@Slf4j
public class MemberUserApi extends BaseApi {
    @Resource
    private IMemberService memberService;
    @Resource
    private ILoginInfoService loginInfoService;
    @Resource
    private IGroupService groupService;
    @Resource
    private IDepartmentService departmentService;
    @Resource
    private TokenFilter tokenFilter;
    @Resource
    private IUserService<UserModel> userService;

    @Resource
    private LoginServiceComposite loginServiceComposite;

    @Resource
    private NormalLogRecordsService normalLogRecordsService;

//    @Resource
//    private IGroupLogRuleService groupLogRuleService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private IGroupIpReService groupIpReService;
    @Resource
    private PushService pushService;
//    @Resource
//    private RocketMQTemplate rocketMQTemplate;
    @Resource
    private DiamondConfig diamondConfig;
    @Resource
    private UserLoginVersionMongoRepository userLoginVersionMongoRepository;
    private static final long TICKS_AT_EPOCH = 621355968000000000L;
    private static final long TICKS_PER_MILLISECOND = 10000;
//    @Value("${zt.pre}")
//    private String preUrl;
//    @Value("${zt.code}")
//    private String getCodeUrl;
//    @Value("${zt.token}")
//    private String getAccessToken;
//    @Value("${zt.userInfo}")
//    private String getUserInfo;

    @Resource
    private IUserDeviceService userDeviceService;

    private final String BOOK_TOKEN = "FROM_ZHI_TU";

    @GetMapping("/admin-page")
    @Operation(summary = "管理学生列表")
    @Roles({Role.admin})
    @RequireContext(value = com.caishi.lkx.common.context.Role.CHANNEL)
    public IPage<Map<String, Object>> adminPage(@ModelAttribute Page<MemberModel> page,
                                                @ModelAttribute MemberModel model,
                                                String account, String keyword,
                                                Boolean owner, Integer groupId,
                                                @RequestParam(required = false) List<String> times,
                                                @RequestParam(defaultValue = "false") Boolean loginInfo,
                                                @RequestParam(required = false) Boolean scope) {
        Map<String, Object> query = clearReturnEmptyStr(model.toMap());
        if (CollUtil.isNotEmpty(times)) {
            query.put("startTime", times.get(0));
            query.put("endTime", times.get(1));
        }
        if (StrUtil.isNotBlank(account)) {
            query.put("account", account);
        }
        query.put("keyword", keyword);
        query.put("owner", owner);
        query.put("groupId", context.getGroupId());
        query.put("scope", scope); //考研查询用户 只查询考研
        query.put("member", true);
        //query.put("haveType", userContext.currentPlatform().convertHaveType());
        IPage<MemberModel> result = memberService.search(clearReturnEmptyStr(query), page, page.searchCount());
        IPage<Map<String, Object>> data = result.convert((d) -> {
            d.setMobile(CommonUtil.mobileSafe(d.getMobile()));
            return BeanUtil.beanToMap(d);
        });
        return data.setRecords(data.getRecords().parallelStream().peek(d -> {
            if (loginInfo) {
                d.put("loginInfo", loginInfoService.userLastLoginData(d.get("id").toString()));
            }
            if (null != d.get("groupId")) {
                d.put("groupName", groupService.queryName((Long) d.get("groupId")));
            }
            LoginInfoModel userLoginInfo = loginInfoService.selectUserLoginInfo(d.get("id").toString(), UserAccountType.username);
            if (null != userLoginInfo) {
                d.put("account", userLoginInfo.getAccount());
            }
            if (null != d.get("departmentId")) {
                d.put("departmentName", departmentService.queryName((Long) d.get("departmentId")));
            }
        }).toList());
    }

    @GetMapping("/by-user-key")
    @Roles
    public MemberModel ByuserKey(String userKey) {
        return memberService.selectFirst(Wrappers.<MemberModel>lambdaQuery().eq(MemberModel::getUserKey, userKey));
    }

    @Roles(value = {Role.admin, Role.channelBusiness,}, roles = {"agentAdmin"})
    @GetMapping("/detail")
    public Object adminMemberDetail(@RequestParam String id) {
        MemberModel model = memberService.getUserDetail(id);
        LoginInfoModel loginInfoModel = loginInfoService.selectFirst(Wrappers.<LoginInfoModel>lambdaQuery().eq(LoginInfoModel::getUserId, id).eq(LoginInfoModel::getLoginType, UserAccountType.username).isNotNull(LoginInfoModel::getCertificate));
        String groupName = null;
        if (null != model.getGroupId()) {
            groupName = groupService.queryName(model.getGroupId());
        }
        LoginExpandModel lastLogin = loginInfoService.userLastLoginData(id);
        if (null != loginInfoModel) {
            return MapUtil.<String, Object>builder().putAll(BeanUtil.beanToMap(model)).put("loginInfo", lastLogin).put("groupName", groupName).put("userName", loginInfoModel.getAccount()).build();
        }
        return MapUtil.<String, Object>builder().putAll(BeanUtil.beanToMap(model)).put("loginInfo", lastLogin).put("groupName", groupName).build();

    }

    @Operation(summary = "学生信息修改")
    @PutMapping("/update")
    public MemberModel edit(@ModelAttribute MemberModel entity) {
        entity.setId(userContext.currentUserId());
        entity.setGroupId(null);
        MemberModel model = memberService.update(entity);
        memberService.sendVers6(userContext.currentUserId(), entity.getHeader(), true);
        return model;
    }

    @PutMapping("/reBind")
    @Operation(summary = "前台用户绑定机构")
    @Parameters({@Parameter(name = "longitude", description = "经度"), @Parameter(name = "latitude", description = "纬度"), @Parameter(name = "groupId", description = "绑定的机构id"),})
    public String bind(HttpServletResponse response, HttpServletRequest request, @RequestParam(defaultValue = "PcZhiYe") UserLogSourceType userLogSourceType) {
        if (memberService.bindGroup(userContext.currentUserId(), userContext.currentLocalGroupId())) {
            //registerLog(userLogSourceType, request, userContext.currentLocalGroupId(), userContext.currentUserId(), userContext.currentIp());
            return loginServiceComposite.resetToken(response);
        }
        return null;
    }

    @PutMapping("/bindByIpL")
    @Operation(summary = "根据ip或者经纬度绑定机构")
    @EncryptionApi
    public String bindByIpL(HttpServletResponse response, HttpServletRequest request, @RequestParam(required = false) BigDecimal longitude, @RequestParam(required = false) BigDecimal latitude, @RequestParam(defaultValue = "AppZhiYe") UserLogSourceType userLogSourceType) {
//        var locationGroup = groupService.currentGroup(userContext.currentIp(), longitude, latitude, null);
//        if (null == locationGroup) {
//            throw new BizRuntimeException(UserResultCode.groupBindFail);
//        }
//        if (memberService.bindGroup(userContext.currentUserId(), locationGroup.getId())) {
//            registerLog(userLogSourceType, request, locationGroup.getId(), userContext.currentUserId(), userContext.currentIp());
//            return loginServiceComposite.resetToken(response);
//        }
        return null;
    }

    @Operation(summary = "根据code绑定机构")
    @Parameters({@Parameter(name = "code", description = "code"), @Parameter(name = "app", description = "true校验时间false不校验时间")})
    @PutMapping("bind-group-by-code")
    @Roles
    public String bindGroupByCode(@RequestParam("code") String code, @RequestParam(defaultValue = "true") Boolean app, @RequestParam(required = false) Long expire, @RequestParam(required = false) String version, @RequestParam(required = false) String userAccount, HttpServletResponse response) throws BizException {
//        Long groupId = null;
//        if (StrUtil.isNotBlank(version) && version.equals("6.0")) {
//            LocalDateTime localDateTime;
//            if (expire.toString().length() == 11) {
//                localDateTime = Instant.ofEpochMilli(expire).atZone(ZoneOffset.ofHours(8)).toLocalDateTime();
//            } else {
//                long ticks = expire;
//                Date date = new Date((ticks - TICKS_AT_EPOCH) / TICKS_PER_MILLISECOND);
//                Instant instant = date.toInstant();
//                ZoneId zoneId = ZoneId.systemDefault();
//                localDateTime = instant.atZone(zoneId).toLocalDateTime();
//            }
//
//            GroupModel groupModel = groupService.selectOne(Wrappers.<GroupModel>lambdaQuery().eq(GroupModel::getGroupCode, code));
//            if (null != groupModel) {
//                groupId = groupModel.getId();
//                if (LocalDateTime.now().isAfter(localDateTime)) {
//                    if (!(groupModel.getQrCodeExpire() != null && LocalDateTime.now().isBefore(groupModel.getQrCodeExpire()))) {
//                        throw new BizRuntimeException(UserResultCode.expireQrcode);
//                    }
//                }
//            }
//
//
//        } else {
//            JSONObject data = groupService.decryptGroupId(code);
//            LocalDateTime localDateTime = data.get("time", LocalDateTime.class);
//            if (null == localDateTime) {
//                throw new BizRuntimeException(UserResultCode.invalidQRcode);
//            }
//            LocalDateTime expirationTime = data.get("expirationTime", LocalDateTime.class);
//            LocalDateTime localDateTime1 = localDateTime.plusSeconds(60);
//            GroupModel groupModel = groupService.getById(data.getLong("groupId"));
//            if (localDateTime1.isBefore(LocalDateTime.now()) && null == expirationTime && app) {
//                if (!(groupModel != null && groupModel.getQrCodeExpire() != null && LocalDateTime.now().isBefore(groupModel.getQrCodeExpire()))) {
//                    throw new BizRuntimeException(UserResultCode.expireQrcode);
//                }
//            }
//            if (null != expirationTime && LocalDateTime.now().isAfter(expirationTime)) {
//                if (!(groupModel != null && groupModel.getQrCodeExpire() != null && LocalDateTime.now().isBefore(groupModel.getQrCodeExpire()))) {
//                    throw new BizRuntimeException(UserResultCode.expireQrcode);
//                }
//            }
//            groupId = data.getLong("groupId");
//        }
//        if (null == groupId) {
//            throw new BizRuntimeException(UserResultCode.invalidQRcode);
//        }
//        String userId = userContext.currentUserId();
//        if (null != userAccount) {
//            TokenData tokenData = userContext.currentTokenData();
//            tokenData.setUserTypeName(UserType.member.name());
//            LoginInfoModel loginInfoModel = loginInfoService.selectLoginInfoUserAccount(userAccount, UserAccountType.username);
//            if (null != loginInfoModel) {
//                userId = loginInfoModel.getUserId();
//                tokenData.setInfoId(loginInfoModel.getId());
//            } else {
//                MemberModel model = memberService.fetchVersRegister(userAccount);
//                userId = model.getId();
//                List<LoginInfoModel> loginInfoModels = loginInfoService.selectUserLoginInfo(userId);
//                tokenData.setInfoId(loginInfoModels.get(0).getId());
//            }
//
//
//        }
//        Boolean aBoolean = memberService.bindGroup(userId, groupId);
//        if (aBoolean) {
//            var versionData = userLoginVersionMongoRepository.findOne(Example.of(UserLoginVersionModel.builder().userId(userId).build())).orElse(null);
//            Long finalGroupId = groupId;
//            String finalUserId = userId;
//            SysThreadPool.execute(() -> {
//                if (null != versionData) {
//                    try {
//                        pushService.sendProjectMessage(versionData.getPcUUid(), AclResultCode.bindGroup.name(), MapUtil.builder().put("groupId", finalGroupId).put("userId", finalUserId).build(), PushService.PushType.online, 0);
//                    } catch (Exception e) {
//                        log.error("websocket发送消息错误", e);
//                    }
//                }
//            });
//            return loginServiceComposite.resetToken(response);
//        }
        return null;
    }

    @PutMapping("reBindBack")
    @Roles({Role.admin})
    public Boolean bindBack(String userId, Long groupId, HttpServletRequest request, HttpServletResponse response) {
        if (StrUtil.isBlank(userId) || null == groupId) {
            throw new BizRuntimeException("参数错误");
        }
        if (memberService.bindBack(userId, groupId, null)) {

            //registerLog(UserLogSourceType.AppGjtk, request, groupId, userId, userContext.currentIp());
            return true;
        }

        return false;
    }

    @PutMapping("/unBind")
    @Operation(summary = "用户解绑机构")
    @Transactional
    public String unBind(String id, HttpServletResponse response) {
        if (StrUtil.isBlank(id)) {
            //carsi身份解绑
            String userId = userContext.currentUserId();
            MemberModel model = memberService.getById(userId);
            if (model.getChannelType().equals(UserChannelType.carsi)) {
                model.setChannelType(UserChannelType.pcWeb7);
                memberService.update(model);
            }
        }
        if (memberService.unBindGroup(StrUtil.isBlank(id) ? userContext.currentUserId() : id)) {
            if (StrUtil.isBlank(id)) {
                return loginServiceComposite.resetToken(response);
            }
        }
        return null;
    }

    @PutMapping("/updateExpireDate")
    @Operation(summary = "用户延长过期时间")
    @Parameters({@Parameter(name = "id", description = "用户id"),})
    public String updateExpireDate(String id, HttpServletResponse response) {
        var res = memberService.updateExpireDate(StrUtil.isBlank(id) ? userContext.currentUserId() : id, userContext.currentLocalGroupId());
        if (res && StrUtil.isBlank(id)) {
            return loginServiceComposite.resetToken(response);
        }
        return null;
    }

    @PutMapping("/updateExpireDateBack")
    @Roles({Role.admin})
    public Boolean updateExpireDateBack(String id) {
        return memberService.updateExpireDate(id);
    }

    @Roles({Role.admin})
    @PostMapping("/import-member")
    @Operation(summary = "导入用户")
    public Boolean importChapter(@RequestParam("file") MultipartFile file, @RequestParam(required = false) Long groupId, @RequestParam(defaultValue = "pcAdmin7") UserChannelType channelType) throws Exception {
        return memberService.importMember(file, null == groupId ? userContext.currentGroupId() : groupId, channelType, userContext.currentUserId());
    }

    @PostMapping("save")
    @Roles({Role.admin})
    @Operation(summary = "新增用户")
    public Boolean saveMemberUser(@RequestBody RegisterMemberDto memberDto, HttpServletRequest request) throws BizException {
        Long groupId = userContext.currentGroupId();
        String userId = userContext.currentUserId();
        boolean vers7 = userContext.currentPlatform().equals(PlatformType.VERS7);
        if (StrUtil.isBlank(memberDto.getUserName()) || null == memberDto.getPassword() || null == memberDto.getDepartmentId() || null == memberDto.getExpireTime()) {
            throw new BizRuntimeException();
        }
        LocalDateTime expireTime = memberDto.getExpireTime();
        GroupModel groupModel = groupService.getById(groupId);
//        LocalDate expireGroupTime = vers7 ? groupModel.getExpireTime() : groupModel.getKaoyanExpireTime();
//        if (expireTime.isAfter(expireGroupTime.atTime(23, 59, 59)) && !expireTime.toLocalDate().isEqual(LocalDate.now())) {
//            throw new BizRuntimeException("用户过期时间超过机构过期时间");
//        }
        Long res = loginInfoService.selectCount(Wrappers.<LoginInfoModel>lambdaQuery().eq(LoginInfoModel::getAccount, memberDto.getUserName()).eq(LoginInfoModel::getLoginType, UserAccountType.username));
        if (res > 0) {
            throw new BizRuntimeException("该用户名已经存在");
        }
        String channelcode = request.getHeader("channelcode");
        memberDto.setType(UserChannelType.valueOf(channelcode));
        return memberService.addMember(groupId, userId, memberDto);
    }

    @GetMapping("index-page")
    @Operation(summary = "前台用户管理")
    public IPage<IndexMemberSearchVo> indexPage(@ModelAttribute Page<IndexMemberSearchVo> page, @ModelAttribute IndexMemberSearchVo searchVo) {
        Long groupId = userContext.currentGroupId();
        searchVo.setGroupId(groupId);
        Map<String, Object> map = clearReturnEmptyStr(BeanUtil.beanToMap(searchVo));
        IPage<IndexMemberSearchVo> res = memberService.searchIndex(page, map);
        boolean ky = userContext.currentPlatform().equals(PlatformType.KAOYAN);
        List<IndexMemberSearchVo> memberSearchVoStream = res.getRecords().parallelStream().peek(m -> {
            UserModel one = userService.selectOne(Wrappers.<UserModel>lambdaQuery().eq(UserModel::getId, m.getCreatedBy()).select(UserModel::getName));
            if (one != null) {
                m.setCreatedBy(one.getName());
            }
            if (ky) {
                m.setExpireTime(m.getKaoyanExpireTime());
            }
            DepartmentModel departmentModel = departmentService.getById(m.getDepartment());
            m.setDepartmentName(departmentModel != null ? departmentModel.getName() : null);
        }).toList();
        res.setRecords(memberSearchVoStream);
        return res;
    }

    @DeleteMapping("/deletes")
    @Operation(summary = "机构删除用户")
    public Boolean delUser(@RequestParam List<String> ids) {
        memberService.deleteUser(ids, userContext.currentGroupId());
        return true;
    }

    @DeleteMapping("logoff")
    @Operation(summary = "用户注销")
    public Boolean logoff(HttpServletResponse response) throws InterruptedException, TimeoutException {
        memberService.logoff(userContext.currentUserId());
        tokenFilter.responseRemoveToken(userContext.currentTokenData().getDevice(), response);
        return true;
    }

    @PutMapping("/edit")
    @Operation(summary = "修改用户")
    public Boolean editMember(@RequestBody RegisterMemberDto registerMemberDto) {
        Long groupId = userContext.currentGroupId();
        LocalDateTime expireTime = registerMemberDto.getExpireTime();
        GroupModel groupModel = groupService.getById(groupId);
//        LocalDate groupExpire = userContext.currentPlatform().equals(PlatformType.VERS7) ? groupModel.getExpireTime() : groupModel.getKaoyanExpireTime();
//        if (expireTime.isAfter(groupExpire.atTime(23, 59, 59)) && !expireTime.toLocalDate().isEqual(LocalDate.now())) {
//            throw new BizRuntimeException("用户过期时间超过机构过期时间");
//        }
        memberService.updateMember(registerMemberDto);
        return true;
    }

    private void registerLog(UserLogSourceType userLogSourceType, HttpServletRequest request, Long groupId, String userId, String ip) {
        if (userContext.currentPlatform().equals(PlatformType.KAOYAN)) {
//            try {
//                RegisterUserLogDto logDto = RegisterUserLogDto.builder()
//                        .userId(userId)
//                        .groupId(groupId)
//                        .sourceType(request.getHeader("platform"))
//                        .ip(ip)
//                        .count(1)
//                        .image(MapUtil.<String, Object>builder()
//                                .put("gid", GroupFilter.getGid(request))
//                                .put("ua", request.getHeader("User-Agent"))
//                                .put("path", request.getHeader("Referer")).build()).build();
//                rocketMQTemplate.sendOneWay("registerUserLog", logDto);
//            } catch (Exception e) {
//                log.error("发送用户日志:{}", e);
//            }


        } else {
//            var c = groupLogRuleService.getMachiningCount(groupId, UserLogType.registerLog, userLogSourceType, null, userId, ip, 1);
//            normalLogRecordsService.addTodayData(UserLogType.registerLog, groupId, userLogSourceType, null, c, 1);
//            normalLogRecordsService.addTodayData(UserLogType.registerLog, -1L, userLogSourceType, null, c, 1);
//            normalLogRecordsService.saveRecordImage(UserLogType.registerLog, null, null, List.of(groupId, -1L), userId, ip, MapUtil.builder().put("gid", GroupFilter.getGid(request)).put("ua", request.getHeader("User-Agent")).put("path", request.getHeader("Referer")).build());
        }

    }


//    @Operation(summary = "获取用户做题记录")
//    @GetMapping("question-count")
//    public Map<LocalDate, Integer> getQuestionCountByCategoryId(Long categoryId, String group) {
//        String userId = userContext.currentUserId();
//        LocalDate date = this.getDays(group);
//        Query query = new Query(Criteria.where("userId").is(userId).and("categoryId").is(categoryId).and("date").gte(date).lte(LocalDate.now())).with(Sort.by(Sort.Order.asc("date")));
//        Map<LocalDate, Integer> map = new HashMap<>();
//        List<UserQuestionRecord> records = mongoTemplate.find(query, UserQuestionRecord.class);
//        while (!date.isEqual(LocalDate.now())) {
//            boolean flag = true;
//            for (UserQuestionRecord userQuestionRecord : records) {
//                if (userQuestionRecord.getDate().isEqual(date)) {
//                    map.put(date, userQuestionRecord.getCount());
//                    flag = false;
//                    break;
//                }
//            }
//            if (flag) {
//                map.put(date, 0);
//            }
//            date = date.plusDays(1);
//        }
//        return map;
//    }



    private LocalDate getDays(String group) {
        LocalDate now = LocalDate.now();
        return switch (group) {
            case "week" -> now.minusDays(7);
            case "month" -> now.minusDays(30);
            default -> throw new BizRuntimeException("参数错误");
        };
    }

    @Operation(summary = "更新token")
    @GetMapping("/update-token")
    public String updateToken(HttpServletResponse response) {
        return loginServiceComposite.resetToken(response);
    }


    //@GetMapping("/zt-code")
    //@Roles
//    public Boolean ztCode(@RequestParam("code") String code) throws BizException {
//        log.info("传入的code{}", code);
//        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
//        Map<String, Object> paramMap = new HashMap<>();
//        paramMap.put("code", code);
//        String urlStr = preUrl + getCodeUrl;
//        log.info("请求的接口{}", urlStr);
//        HttpRequest request = HttpUtil.createGet(urlStr);
//        request.header("Content-Type", "application/json;charset=UTF-8");
//        request.form(paramMap);
//        request.timeout(5000);
//        HttpResponse response1 = request.execute();
//        if (response1.getStatus() != 200) {
//            throw new RuntimeException("获取用户信息失败");
//        }
//        JSONObject jsonObject = JSON.parseObject(response1.body(), JSONObject.class);
//        if (!jsonObject.getStr("statusCode").equals("200")) {
//            throw new BizRuntimeException(jsonObject.getStr("errors"));
//        }
//        jsonObject = jsonObject.getJSONObject("data");
//        log.info("得到的body{}", jsonObject);
//        String orgCode = jsonObject.getStr("orgCode");
//        if (null == orgCode) orgCode = "cqu";
//        String userKey = jsonObject.getStr("userKey");
//        String accessTokenUrl = preUrl + getAccessToken;
//        log.info("请求的接口{}", accessTokenUrl);
//        paramMap.clear();
//        paramMap.put("code", code);
//        paramMap.put("orgCode", orgCode);
//        if (StrUtil.isNotBlank(userKey)) paramMap.put("userKey", userKey);
//        HttpRequest post = HttpUtil.createPost(accessTokenUrl);
//        post.header("Content-Type", "application/json");
//        post.header("User-Agent", "WPLR");
//        post.body(JSON.toJSONString(paramMap));
//        post.timeout(5000);
//        HttpResponse execute = post.execute();
//        if (execute.getStatus() != 200) {
//            throw new RuntimeException("网络异常");
//        }
//        JSONObject jsonObject1 = JSON.parseObject(execute.body(), JSONObject.class);
//
//        jsonObject1 = jsonObject1.getJSONObject("data");
//        log.info("得到的body{}", jsonObject1);
//        String token = jsonObject1.getStr("token");
//        String expired = jsonObject1.getStr("tokenExpiredAt");
//        Cookie cookie = new Cookie(BOOK_TOKEN, token);
//        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
//        try {
//            Date date = df1.parse(expired);
//            Date date1 = new Date();
//            long between = DateUtil.between(date1, date, DateUnit.SECOND);
//            cookie.setMaxAge(Long.valueOf(between).intValue());
//        } catch (ParseException e) {
//            log.error("token过期时间转换失败", e);
//        }
//        cookie.setPath("/");
//        response.addCookie(cookie);
//        log.info("智图的cookie{}", cookie);
//        login(response, paramMap, orgCode, userKey, token);
//        return true;
//    }

//    @GetMapping("/zt-login")
//    @Roles
//    private Boolean ztLogin(@RequestParam String token) throws BizException {
//        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
//        Map<String, Object> paramMap = new HashMap<>();
//        paramMap.put("token", token);
//        String accessTokenUrl = preUrl + "/open/OAuth/GetBaseInfo";
//        HttpRequest post = HttpUtil.createPost(accessTokenUrl);
//        post.header("Content-Type", "application/json");
//        post.header("User-Agent", "WPLR");
//        post.body(JSON.toJSONString(paramMap));
//        post.timeout(5000);
//        HttpResponse execute = post.execute();
//        if (execute.getStatus() != 200) {
//            throw new RuntimeException("网络异常");
//        }
//        JSONObject jsonObject = JSON.parseObject(execute.body(), JSONObject.class);
//        if (!jsonObject.getStr("statusCode").equals("200")) {
//            throw new BizRuntimeException(jsonObject.getStr("errors"));
//        }
//        jsonObject = jsonObject.getJSONObject("data");
//        String orgCode = jsonObject.getStr("orgCode");
//        String userKey = jsonObject.getStr("userKey");
//        if (userKey == null || orgCode == null) {
//            return false;
//        } else {
//            login(response, paramMap, orgCode, userKey, token);
//        }
//        return true;
//    }

//    private void login(HttpServletResponse response, Map<String, Object> paramMap, String orgCode, String userKey, String token) throws BizException {
//        log.info("userkey：{}", userKey);
//        if (userKey != null) {
//            MemberModel userModel = memberService.selectOne(Wrappers.<MemberModel>lambdaQuery().eq(MemberModel::getUserKey, userKey));
//            //GroupModel groupModel = groupService.selectOne(Wrappers.<GroupModel>lambdaQuery().eq(GroupModel::getZhituTag, orgCode));
//
//            String userId;
//            if (null == userModel) {
//                String url = preUrl + getUserInfo;
//                paramMap.clear();
//                paramMap.put("userKey", userKey);
//                paramMap.put("orgCode", orgCode);
//                HttpRequest uerPost = HttpUtil.createPost(url);
//                uerPost.header("Content-Type", "application/json;charset=UTF-8");
//                uerPost.header("User-Agent", "WPLR");
//                uerPost.header("Authorization", "Bearer " + token);
//                uerPost.body(JSON.toJSONString(paramMap));
//                uerPost.timeout(5000);
//                HttpResponse execute1 = uerPost.execute();
//                if (execute1.getStatus() != 200) {
//                    log.info(String.valueOf(execute1.getStatus()));
//                    throw new RuntimeException("网络异常");
//                }
//                JSONObject jsonObject2 = JSON.parseObject(execute1.body(), JSONObject.class);
//                JSONObject data = jsonObject2.getJSONObject("data");
//                String username = data.getStr("name");
//                Sex sex = Sex.getSex(data.getStr("gender"));
//                MemberModel member = new MemberModel();
////                if (ObjectUtil.isNotEmpty(groupModel)) {
////                    member.setGroupId(groupModel.getId());
////                    LocalDateTime expire = groupService.getUserExpireTime(groupModel, userContext.currentPlatform()).atTime(23, 59, 59);
////                    if (userContext.currentPlatform().equals(PlatformType.VERS7)) {
////                        member.setExpireTime(expire);
////                    } else {
////                        member.setKaoyanExpireTime(expire);
////                    }
////                    member.addUserType(UserType.groupMember);
////                } else {
////                    GroupModel groupModel1 = groupService.selectOne(Wrappers.<GroupModel>lambdaQuery().eq(GroupModel::getName, "维普考研"));
////                    member.setGroupId(groupModel1.getId());
////                    member.setKaoyanExpireTime(LocalDateTime.now().plusDays(30));
////                    member.addUserType(UserType.groupMember);
////                }
//                member.setChannelType(UserChannelType.sso);
//                member.setName(username);
//                member.setUserKey(userKey);
//                member.setSex(sex);
//
//                UserModel user = loginServiceComposite
//                        .register(LoginInfoModel.builder()
//                                .loginType(UserAccountType.username)
//                                .account(userKey)
//                                .certificate(diamondConfig.getUserDefaultPassword())
//                                .build(), member).toUserModel();
//                userId = user.getId();
//
//            } else {
//                userId = userModel.getId();
////                if (ObjectUtil.isNotEmpty(groupModel)) {
////                    boolean equals = userModel.getGroupId().equals(groupModel.getId());
////                    if (!equals) {
////                        userModel.setGroupId(groupModel.getId());
////                        LocalDateTime expire = groupService.getUserExpireTime(groupModel, userContext.currentPlatform()).atTime(23, 59, 59);
////                        if (userContext.currentPlatform().equals(PlatformType.VERS7)) {
////                            userModel.setExpireTime(expire);
////                        } else {
////                            userModel.setKaoyanExpireTime(expire);
////                        }
////                        memberService.update(userModel);
////                    } else {
////                        userModel.setKaoyanExpireTime(LocalDateTime.now().plusDays(30));
////                        memberService.update(userModel);
////                    }
////                } else {
////                    userModel.setKaoyanExpireTime(LocalDateTime.now().plusDays(30));
////                    memberService.update(userModel);
////                }
//            }
//            LoginDto loginDto = new LoginDto();
//            loginDto.setDeviceType(DeviceType.pc);
//            loginDto.setDeviceName(loginDto.getDeviceType().getDesc());
//            //loginDto.setUserTypes(new UserType[]{UserType.groupMember});
//            LoginInfoModel loginInfoModel = loginInfoService.selectUserLoginInfo(userId, UserAccountType.username);
//            loginServiceComposite.success(loginInfoModel, loginDto, true, response, false);
//        }
//    }



    @PutMapping("/update-userKey")
    @Roles
    public Boolean revise(@RequestParam("code") String code) {
        String md5 = MD5Util.MD5Encode(ZT_ENCODE);
        var aes = new AES(Mode.ECB, Padding.ZeroPadding, md5.getBytes(StandardCharsets.UTF_8));
        JSONObject entries = JSON.parseObject(aes.decryptStr(code, CharsetUtil.CHARSET_UTF_8), JSONObject.class);
        //获取userKey
        String userKey = entries.getStr("userKey");
        String id = entries.getStr("id");
        MemberModel userModel = memberService.getById(id);
        if (null == userModel || StrUtil.isBlank(userKey)) {
            return false;

        }
        userModel.setUserKey(userKey);
        memberService.update(userModel);
        return true;
    }

    @GetMapping("/unbind-carsi")
    @Operation(summary = "解除carsi")
    public Boolean unbindCarsi() {
        String userId = userContext.currentUserId();
        MemberModel model = memberService.getById(userId);
        if (model.getChannelType().equals(UserChannelType.carsi)) {
            model.setChannelType(UserChannelType.pcWeb7);
            memberService.update(model);
            memberService.unBindGroup(userId);
            return true;
        }
        return false;
    }
    @GetMapping("/index-count")
    @Roles({Role.onlyLogin})
    @RequireContext(com.caishi.lkx.common.context.Role.CHANNEL)
    public Map<String, Object> indexCount(@RequestParam(value = "all", defaultValue = "true") Boolean all) {
        Long groupId = context.getGroupId();
        Long total =  memberService.selectCount(Wrappers.<MemberModel>lambdaQuery().eq(!all,MemberModel::getGroupId, groupId));
        Long totalNew = memberService.selectCount(Wrappers.<MemberModel>lambdaQuery().eq(!all,MemberModel::getGroupId, groupId).like(MemberModel::getCreatedTime, LocalDate.now()));
        return  MapUtil.<String, Object>builder().put("total", total).put("todayNew", totalNew).build();
    }

    @GetMapping("/index-line")
    @Roles({Role.onlyLogin})
    @RequireContext(com.caishi.lkx.common.context.Role.CHANNEL)
    public List<Map> indexLine(@RequestParam("startTime") LocalDateTime startTime, @RequestParam("endTime") LocalDateTime endTime, @RequestParam("timeType") String timeType, @RequestParam(value = "all", defaultValue = "true") Boolean all) {
        Map<String, Object> map = new HashMap<>();
        if (!all) {
           map.put("groupId", context.getGroupId());
        }

        String format = "%Y-%m-%d";
        if ("year".equals(timeType)) {
            format = "%Y-%m";
        }
        map.put("timeType", format);
        map.put("startTime", startTime);
        map.put("endTime", endTime);
       return memberService.countLine(map);
    }
    public static void main(String[] args) {
        String md5 = MD5Util.MD5Encode(ZT_ENCODE);
        var aes = new AES(Mode.ECB, Padding.ZeroPadding, md5.getBytes(StandardCharsets.UTF_8));
        JSONObject entries = new JSONObject();
        entries.set("userKey", "cqu_vipsmart00001");
        entries.set("username", "klfzs");
        entries.set("groupCode", "sicnu");
        String s = aes.encryptBase64(entries.toString());
        String decryptStr = aes.decryptStr("+J5qn9aaKJMAwgo2Aq8WoOo+Q9tSa197dyJa1pyhpv06NUxYq27FIFk4/2DVYiya", CharsetUtil.CHARSET_UTF_8);
        System.out.println(decryptStr);
        System.out.println(s);
    }
}
